package com.jincheng.web.controller.common;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.jincheng.common.core.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * ClassName: OSSController
 * Package: com.jssvc.mentalhealth.controller
 * Description:
 *
 * @Author 严桂江
 * @Create 2023-4-3 22:30
 * @Version 1.0
 */

/**
 * 阿里云OSS
 */
@CrossOrigin
@RestController
@RequestMapping("/oss")
public class OSSController {

    private static final Logger log = LoggerFactory.getLogger(OSSController.class);
    @Value("${aliyun.access-key-id}")
    private String accessKeyId;

    @Value("${aliyun.access-key-secret}")
    private String accessKeySecret;

    @Value("${aliyun.bucket-name}")
    private String bucketName;

    @Value("${aliyun.endpoint}")
    private String endpoint;

    @Value("${aliyun.region}")
    private String region;

    @Value("${aliyun.directory}")
    private String dir;

//    // 从配置文件中获取AK和SK
//    private final CredentialsProvider credentialsProvider;
//
//    // OSSClient实例。
//    private final ClientBuilderConfiguration clientBuilderConfiguration;
//
//    // OSS实例。
//    private final OSS ossClient;
//
//    {
//        credentialsProvider = new DefaultCredentialProvider(accessKeyId, accessKeySecret);
//        clientBuilderConfiguration = new ClientBuilderConfiguration();
//        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
//        ossClient = OSSClientBuilder.create()
//                .endpoint(endpoint)
//                .credentialsProvider(credentialsProvider)
//                .clientConfiguration(clientBuilderConfiguration)
//                .region(region)
//                .build();
//    }

    @GetMapping("/policy")
    public AjaxResult policy() {
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        // 创建ossClient实例。

        long expireTime = 600;
        long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
        // 设置过期时间
        Date expiration = new Date(expireEndTime);
        PolicyConditions policyConditions = new PolicyConditions();

        // 添加条件项
        policyConditions.addConditionItem("content-length-range", 0, 1048576000);
        policyConditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String encodedPolicy = null;
        String postSignature = null;

        try {
            // 获取Policy
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
            encodedPolicy = BinaryUtil.toBase64String(binaryData);
            postSignature = ossClient.calculatePostSignature(postPolicy);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        } finally {
            ossClient.shutdown();
        }

        // 像前端返回Policy信息
        AjaxResult ajax = AjaxResult.success();
        ajax.put("accessId", accessKeyId);
        ajax.put("policy", encodedPolicy);
        ajax.put("signature", postSignature);
        ajax.put("dir", dir);
        ajax.put("host", "https://" + bucketName + "." + endpoint);
        ajax.put("expire", String.valueOf(expireEndTime / 1000));
        return ajax;
    }

    @DeleteMapping("/delete")
    public AjaxResult delete(@RequestParam("fileUrl") String fileUrl) {
        // 去掉前缀
        fileUrl = fileUrl.replace("https://" + bucketName + "." + endpoint + "/", "");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, fileUrl);
        } catch (OSSException oe) {
            log.error("捕获了一个OSS异常，这意味着您的请求已发送到OSS，但由于某种原因被错误响应拒绝。");
            log.error("Error Message:{}", oe.getErrorMessage());
            log.error("Error Code:{}", oe.getErrorCode());
            log.error("Request ID:{}", oe.getRequestId());
            log.error("Host ID:{}", oe.getHostId());
            return AjaxResult.error("删除失败");
        } catch (ClientException ce) {
            log.error("捕获了一个客户端异常，这意味着客户端在试图与OSS通信时遇到了严重的内部问题，例如无法访问网络。");
            log.error("Error Message:{}", ce.getMessage());
            return AjaxResult.error("删除失败");
        } finally {
            ossClient.shutdown();
        }
        return AjaxResult.success("删除成功");
    }

    @DeleteMapping("/deleteArray")
    public AjaxResult deleteArray(@RequestParam("fileUrls") String[] fileUrls) {


        return AjaxResult.success();
    }
}
